package com.h3bpm.web.instance.consultingReportNumber;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.handler.JSONUtils;
import com.h3bpm.web.common.utils.SqlUtil;
import com.h3bpm.web.config.UrlConfig;
import com.h3bpm.web.instance.applicationAgencyNo.ApplicationAgencyNoController;
import com.h3bpm.web.instance.consultingReportNumber.dao.ReportNoDao;
import com.h3bpm.web.protalHanding.ThreadPost;
import com.h3bpm.web.reback.service.RebackService;
import com.h3bpm.web.util.DateUtil;
import data.DataRow;
import data.DataTable;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author villwang
 * @date 2020/07/20
 **/
@RestController
@RequestMapping("/Portal/Instances")
public class ReportNumberController {
    private static final Logger logger = LoggerFactory.getLogger(ReportNumberController.class);

    @Autowired
    private ReportNoDao reportNoDao;

    @Autowired
    private RebackService rebackService;

    /**
     * 获取报告号并回写
     * @param instanceId
     * @param workflowCode
     * @return
     */
    @RequestMapping("/getReportNoWriteBack")
    public JSONObject getReportNos(String instanceId, String workflowCode){
        synchronized (ReportNumberController.class){
            JSONObject result = new JSONObject();
            String reportNo = getReportNo();
            boolean flag = false;
            logger.info("获咨询报告号————————————————-reportNo:"+reportNo);
            if(StringUtils.isNotBlank(reportNo)){
                flag = addReportNo(instanceId, reportNo);
            }
            logger.info("咨询报告号回写EC————————————————-flag:"+flag);
            if(flag){
                //招标代理号回写OA(流程数据回写OA)
                flag = rebackService.consultingReportNumber(instanceId, workflowCode, reportNo);
            }
            logger.info("咨询报告号回写OA————————————————-flag:"+flag);
            if(flag){
                result.put("state", "200");
                result.put("msg", "success");
            }
            return result;
        }
    }

    //咨询报告号回写EC
    public boolean addReportNo(String instanceId, String reportNo){
        boolean flag = true;
        InstanceData instanceData = null;
        try {
            instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
            BizObject bizObject = instanceData.getBizObject();
            HashMap<String, Object> body = new HashMap<>();
            body.put("businessId", bizObject.GetValue("businessId"));
            body.put("reportNo", org.apache.commons.lang3.StringUtils.isNotBlank(reportNo)?reportNo:(String)bizObject.GetValue("resultDocumentName"));
            body.put("type", bizObject.GetValue("type"));
            body.put("createBy", bizObject.GetValue("userName"));
            body.put("reportName", bizObject.GetValue("resultDocumentName"));
            body.put("reportType", bizObject.GetValue("reportType"));
            body.put("guid", bizObject.GetValue("guid"));
            String url = UrlConfig.BusinessUrl+"/prod-api/workflow/addReportNoNew";
            String json = JSONUtils.toJson(body);
            Map<String, Object> result = ThreadPost.postRequestResult(url,json,null);
            if(result==null||result.size()==0){
                logger.debug("返回值为空—————————————");
            }else {
                int res= (Integer) result.get("code");
                if(res==200){
                    flag = true;
                    logger.debug("更新实例结果====================success");
                }else {
                    logger.debug("更新实例结果====================失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public String getReportNo(){
//        JSONObject result = new JSONObject();
        String data =null;
        try {
        String reportNo="";
        String newReportNo="";
        String newReportNoYear="";
        Integer no=0;
         reportNo = reportNoDao.getMaxReportNo();
         if(StringUtils.isNotBlank(reportNo)){
            if(reportNo.length()>4){
                newReportNo=reportNo.substring(reportNo.length()-4);
            }
             if(reportNo.length()>10){
                 newReportNoYear=reportNo.substring(6,10);
             }
         }
         if(StringUtils.isNotBlank(newReportNo)){
             no=Integer.parseInt(newReportNo);

         }
        if(StringUtils.isNotBlank(newReportNoYear)&&!newReportNoYear.equals(String.valueOf(DateUtil.getYear()))){
            data = "H0703-"+ DateUtil.getYear()+"-"+"0001";
        }else{
            no=no+1;
            String str = "000000" + no.toString();
            str = str.substring(str.length() - 4);
            str = "H0703-"+ DateUtil.getYear()+"-"+str;
            data =  str;
        }
//         logger.info("获取报告号—————————str———————-"+result.get("data"));
//         result.put("state", "200");
//         result.put("msg", "success");
//         return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
    @RequestMapping("/checkReportNo")
    public JSONObject checkReportNo(String reportNo){
        JSONObject result = new JSONObject();
        try {
            if(StringUtils.isNotBlank(reportNo)){
            String newReportNo="";
            String reNo=reportNo;
            Integer no=0;
            String sql="select consultationReportNo from ot_consultingReportNumber ORDER BY CreatedTime desc LIMIT 1";
            DataTable data = null;
            data = SqlUtil.doQuery(sql);
            List<DataRow> entityRows = data.getEntityRows();
            if(!entityRows.isEmpty()&&entityRows.size()>0) {
                reportNo = entityRows.get(0).getString("consultationReportNo");
            }
            if(StringUtils.isNotBlank(reportNo)){
                if(reportNo.length()>6){
                    newReportNo=reportNo.substring(reportNo.length()-4);
                }

            }else {
                result.put("state", "200");
                result.put("data", reNo);
                result.put("msg", "success");
                return result;
            }
            if(StringUtils.isNotBlank(newReportNo)){
                no=Integer.parseInt(newReportNo);

            }

            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return  null;
    }

    @RequestMapping("/getHistoryReportNo")
    public JSONObject getHistoryReportNo(String projectCode, String businessStatus){
        JSONObject result = new JSONObject();
        result.put("state", "200");
        result.put("msg", "success");
        result.put("data", reportNoDao.getHistoryReportNo(projectCode, businessStatus));
        return result;
    }


}
